package demo3;

/**
 * Created with IntelliJ IDEA.
 * Description:克隆接口::克隆一个对象
 * User: LianBao
 * Date: 2024-03-09
 * Time: 19:16
 */

class Money implements Cloneable {
    public double Money = 10.0;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Person implements Cloneable {

    //要想具备克隆的功能,必须实现Cloneable这个接口
    /*
     * Cloneable这个接口里面一个抽象方法也没有,叫空接口(标记接口),只要实现了这个接口,证明当前类才能被克隆
     * */
    public int age;
    public Money m = new Money();

    public Person(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person) super.clone();
        tmp.m = (Money) this.m.clone();
        return tmp;
        //重写克隆方法
    }
}

public class Test {

    public static void main(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person(20);
        Person person2 = (Person) person1.clone();

        //浅拷贝
        System.out.println(person1.m.Money);
        System.out.println(person2.m.Money);
        System.out.println("==============");
        person2.m.Money = 1000.0;
        System.out.println(person1.m.Money);
        System.out.println(person2.m.Money);
    }
}
